package com.team9.fitness.controller;

import com.team9.fitness.entity.CommunityPost;
import com.team9.fitness.service.ZRDDSSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 社区动态管理控制器
 */
@RestController
@RequestMapping("/api/community-posts")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Slf4j
public class CommunityPostController {

    @Autowired
    private ZRDDSSendService zrddsSendService;

    /**
     * 创建帖子
     */
    @PostMapping
    public CompletableFuture<ResponseEntity<Map<String, Object>>> createPost(@RequestBody CommunityPost post) {

        log.info("创建社区帖子请求: userId={}, title={}", post.getUserId(), post.getTitle());

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("post", post);

        return zrddsSendService.sendBusinessRequest("COMMUNITY_CREATE_POST", "POST", "/api/community-posts",
                post.getUserId().toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "帖子创建成功");
                        result.put("data", response.getData());
                        log.info("帖子创建成功: userId={}, title={}", post.getUserId(), post.getTitle());
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "帖子创建失败");
                        log.warn("帖子创建失败: userId={}, title={}, error={}", post.getUserId(), post.getTitle(),
                                response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("帖子创建异常: userId={}, title={}", post.getUserId(), post.getTitle(), throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "帖子创建服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取所有帖子
     */
    @GetMapping
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getAllPosts(
            @RequestParam(required = false) Long currentUserId) {

        log.info("获取所有社区帖子请求: currentUserId={}", currentUserId);

        Map<String, Object> requestBody = new HashMap<>();
        if (currentUserId != null) {
            requestBody.put("currentUserId", currentUserId);
        }

        return zrddsSendService.sendBusinessRequest("COMMUNITY_GET_ALL_POSTS", "GET", "/api/community-posts",
                currentUserId != null ? currentUserId.toString() : null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取帖子成功");
                        result.put("data", response.getData());
                        log.info("获取帖子成功: currentUserId={}", currentUserId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取帖子失败");
                        log.warn("获取帖子失败: currentUserId={}, error={}", currentUserId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取帖子异常: currentUserId={}", currentUserId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取帖子服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取帖子详情（快速加载 - 仅正文 + 前10条评论）
     */
    @GetMapping("/{id}/quick")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getPostByIdQuick(@PathVariable Long id,
            @RequestParam(required = false) Long currentUserId,
            @RequestParam(defaultValue = "10") Integer commentLimit) {

        log.info("快速获取帖子详情请求: postId={}, currentUserId={}, commentLimit={}", id, currentUserId, commentLimit);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("postId", id);
        requestBody.put("commentLimit", commentLimit);
        if (currentUserId != null) {
            requestBody.put("currentUserId", currentUserId);
        }

        return zrddsSendService.sendBusinessRequest("COMMUNITY_GET_POST_QUICK", "GET", "/api/community-posts/" + id + "/quick",
                currentUserId != null ? currentUserId.toString() : null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "快速获取帖子详情成功");
                        result.put("data", response.getData());
                        log.info("快速获取帖子详情成功: postId={}, currentUserId={}, commentLimit={}", id, currentUserId, commentLimit);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "快速获取帖子详情失败");
                        log.warn("快速获取帖子详情失败: postId={}, currentUserId={}, commentLimit={}, error={}", id, currentUserId, commentLimit, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("快速获取帖子详情异常: postId={}, currentUserId={}, commentLimit={}", id, currentUserId, commentLimit, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "服务器内部错误");
                    return ResponseEntity.status(500).body(result);
                });
    }

    /**
     * 获取帖子剩余评论（后台补充加载）
     */
    @GetMapping("/{id}/comments")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getPostComments(@PathVariable Long id,
            @RequestParam(required = false) Long currentUserId,
            @RequestParam(defaultValue = "0") Integer offset,
            @RequestParam(defaultValue = "20") Integer limit) {

        log.info("获取帖子评论请求: postId={}, currentUserId={}, offset={}, limit={}", id, currentUserId, offset, limit);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("postId", id);
        requestBody.put("offset", offset);
        requestBody.put("limit", limit);
        if (currentUserId != null) {
            requestBody.put("currentUserId", currentUserId);
        }

        return zrddsSendService.sendBusinessRequest("COMMUNITY_GET_POST_COMMENTS", "GET", "/api/community-posts/" + id + "/comments",
                currentUserId != null ? currentUserId.toString() : null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取帖子评论成功");
                        result.put("data", response.getData());
                        log.info("获取帖子评论成功: postId={}, currentUserId={}, offset={}, limit={}", id, currentUserId, offset, limit);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取帖子评论失败");
                        log.warn("获取帖子评论失败: postId={}, currentUserId={}, offset={}, limit={}, error={}", id, currentUserId, offset, limit, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取帖子评论异常: postId={}, currentUserId={}, offset={}, limit={}", id, currentUserId, offset, limit, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "服务器内部错误");
                    return ResponseEntity.status(500).body(result);
                });
    }

    /**
     * 获取单个帖子详情（完整版 - 兼容旧接口）
     */
    @GetMapping("/{id}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getPostById(@PathVariable Long id,
            @RequestParam(required = false) Long currentUserId) {

        log.info("获取帖子详情请求: postId={}, currentUserId={}", id, currentUserId);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("postId", id);
        if (currentUserId != null) {
            requestBody.put("currentUserId", currentUserId);
        }

        return zrddsSendService.sendBusinessRequest("COMMUNITY_GET_POST_BY_ID", "GET", "/api/community-posts/" + id,
                currentUserId != null ? currentUserId.toString() : null, requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取帖子详情成功");
                        result.put("data", response.getData());
                        log.info("获取帖子详情成功: postId={}, currentUserId={}", id, currentUserId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取帖子详情失败");
                        log.warn("获取帖子详情失败: postId={}, currentUserId={}, error={}", id, currentUserId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取帖子详情异常: postId={}, currentUserId={}", id, currentUserId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取帖子详情服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取用户帖子列表
     */
    @GetMapping("/user/{userId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getUserPosts(@PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        log.info("获取用户帖子列表请求: userId={}, page={}, size={}", userId, page, size);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("userId", userId);
        requestBody.put("page", page);
        requestBody.put("size", size);

        return zrddsSendService.sendBusinessRequest("COMMUNITY_GET_USER_POSTS", "GET", "/api/community-posts/user/" + userId,
                userId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取用户帖子列表成功");
                        result.put("data", response.getData());
                        log.info("获取用户帖子列表成功: userId={}, page={}, size={}", userId, page, size);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取用户帖子列表失败");
                        log.warn("获取用户帖子列表失败: userId={}, page={}, size={}, error={}", userId, page, size, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取用户帖子列表异常: userId={}, page={}, size={}", userId, page, size, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取用户帖子列表服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 更新帖子
     */
    @PutMapping("/{id}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> updatePost(@PathVariable Long id,
            @RequestBody CommunityPost post) {

        log.info("更新帖子请求: postId={}, userId={}, title={}", id, post.getUserId(), post.getTitle());

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("postId", id);
        requestBody.put("post", post);

        return zrddsSendService.sendBusinessRequest("COMMUNITY_UPDATE_POST", "PUT", "/api/community-posts/" + id,
                post.getUserId().toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "帖子更新成功");
                        result.put("data", response.getData());
                        log.info("帖子更新成功: postId={}, userId={}, title={}", id, post.getUserId(), post.getTitle());
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "帖子更新失败");
                        log.warn("帖子更新失败: postId={}, userId={}, title={}, error={}", id, post.getUserId(), post.getTitle(), response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("帖子更新异常: postId={}, userId={}, title={}", id, post.getUserId(), post.getTitle(), throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "帖子更新服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/{id}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> deletePost(@PathVariable Long id,
            @RequestParam Long userId) {

        log.info("删除帖子请求: postId={}, userId={}", id, userId);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("postId", id);
        requestBody.put("userId", userId);

        return zrddsSendService.sendBusinessRequest("COMMUNITY_DELETE_POST", "DELETE", "/api/community-posts/" + id,
                userId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "帖子删除成功");
                        result.put("data", response.getData());
                        log.info("帖子删除成功: postId={}, userId={}", id, userId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "帖子删除失败");
                        log.warn("帖子删除失败: postId={}, userId={}, error={}", id, userId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("帖子删除异常: postId={}, userId={}", id, userId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "帖子删除服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }
}
